package com.UnionPayCenter.service.serviceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.UnionPayCenter.coupon.service.CouponQueryService;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.UnionPayCenter.constant.ConstantInterface;
import com.UnionPayCenter.entity.ConfEntity;
import com.UnionPayCenter.entity.ManagerEntity;
import com.UnionPayCenter.entity.WhiteListEntity;
import com.UnionPayCenter.entity.WhitelistSetEntity;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.mapper.ConfMapper;
import com.UnionPayCenter.mapper.ManagerMapper;
import com.UnionPayCenter.mapper.WhiteListMapper;
import com.UnionPayCenter.service.IWhiteListService;
import com.UnionPayCenter.util.CSVUtil;
import com.UnionPayCenter.util.DateFormatUtil;
import com.UnionPayCenter.util.PhoneCheckUtil;
import com.UnionPayCenter.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
@Transactional
public class WhiteListServiceImpl implements IWhiteListService {
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private WhiteListMapper whiteListMapper;
    @Autowired
    private ConfMapper confMapper;

    @Autowired
    private CouponQueryService couponQueryService;

    @Override
    public PageInfo<WhiteListEntity> findList(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            // 页数
            Integer page = jsonParam.getInteger("page");
            if (page == null) {
                page = 1;
            }
            // 每页条数
            Integer pageSize = jsonParam.getInteger("pageSize");
            if (pageSize == null) {
                pageSize = 20;
            }
            PageHelper.startPage(page, pageSize);

            String mobile = jsonParam.getString("mobile");
            List<WhiteListEntity> list = whiteListMapper.selectList(shopId, mobile);
            PageInfo<WhiteListEntity> pageList = new PageInfo<>(list);
            return pageList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean add(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            String mobile = jsonParam.getString("mobile");
            WhiteListEntity whiteListEntity = whiteListMapper.selectByMobile(mobile, shopId);
            if (whiteListEntity != null) {
                throw new ApiException(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), "该手机号已存在"));
            } else {
                whiteListEntity = new WhiteListEntity();
                whiteListEntity.setMobile(mobile);
                whiteListEntity.setShopId(shopId);
                whiteListMapper.insertSelective(whiteListEntity);
            }
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean delete(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Integer wlId = jsonParam.getInteger("wlId");
            //判断是否存在
            WhiteListEntity exists = whiteListMapper.selectByWhitelistId(wlId);
            if (exists == null) {
                throw new ApiException(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), "wlId已删除或不存在"));
            }
            
            WhiteListEntity whiteListEntity = new WhiteListEntity();
            whiteListEntity.setWlId(wlId);
            //删除将状态改为1
            whiteListEntity.setStatus(1);
            whiteListMapper.updateByPrimaryKeySelective(whiteListEntity);
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public String exportModel(JSONObject jsonParam) throws IOException {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            List<WhiteListEntity> wlList = whiteListMapper.selectList(shopId, "");
            
            String[] propertyName = new String[1];
            propertyName[0] = "手机号";

            List<List<String>> exportData = new ArrayList<List<String>>();
            List<String> row;
            if (wlList != null) {
                row = new ArrayList<>();
                row.add("");
                exportData.add(row);
            }

            String name = "/WhiteListTemplate-" + DateFormatUtil.getYYYY_MM_DD() + ".xls";
            CSVUtil.poiExcel(name, "白名单导入模版", propertyName, exportData);

            ConfEntity confEntity = confMapper.selectByKey(ConstantInterface.DOMAIN_URL);
            return confEntity.getConfValue() + name;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public List<WhiteListEntity> importWhiteList(Integer managerId, Integer shopId, MultipartFile file) throws IOException {
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            if (managerEntity.getShopId() == null) {
                throw new ApiException(ErrorCodeEnum.SW200);
            }

            boolean notNull = false;
            String fileName = file.getOriginalFilename();
            List<WhiteListEntity> whiteList = new ArrayList<>();
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$") && !fileName.matches("^.+\\.(?i)(csv)" +
                    "$")) {
                throw new ApiException(ErrorCodeEnum.SW300);
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            Sheet sheet = wb.getSheetAt(0);
            if (sheet != null) {
                notNull = true;
            }
            WhiteListEntity wlEntity;
            DecimalFormat df = new DecimalFormat("#");
            for (int r = 2; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);//通过sheet表单对象得到 行对象

                String mobile = "";
                if (row.getCell(0).getCellType() == 0) {
                    mobile = df.format(row.getCell(0).getNumericCellValue());
                } else {
                    mobile = row.getCell(0).getStringCellValue();
                }
                if (StringUtils.isNullStr(mobile)) {
                    throw new ApiException(ErrorCodeEnum.SW301.code(), String.format(ErrorCodeEnum.SW301.msg(), (r + 1) + "行，手机号有误"));
                }
                if (!PhoneCheckUtil.isPhoneLegal(mobile)) {
                    throw new ApiException(ErrorCodeEnum.SW301.code(), String.format(ErrorCodeEnum.SW301.msg(), (r + 1) + "行，手机号不规范"));
                }
                
                WhiteListEntity exists = whiteListMapper.selectByMobile(mobile, shopId);
                if (exists != null) {
                    throw new ApiException(ErrorCodeEnum.SW301.code(), String.format(ErrorCodeEnum.SW301.msg(), (r + 1) + "行，白名单中已存在该手机号"));
                }

                wlEntity = new WhiteListEntity();
                wlEntity.setMobile(mobile);
                wlEntity.setShopId(shopId);

                whiteList.add(wlEntity);
            }
            //插入数据库
            Timestamp now = new Timestamp(Calendar.getInstance().getTimeInMillis());
            for (WhiteListEntity wl : whiteList) {
                wl.setCreateDate(now);
                whiteListMapper.insertSelective(wl);
            }

            return whiteList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean setWhitelist(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Integer levelId = jsonParam.getInteger("levelId");
            if (levelId != null && levelId <= 0) {
                throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "levelId"));
            }
            
            JSONArray couponList = jsonParam.getJSONArray("couponList");
            
            WhitelistSetEntity setEntity;
            List<WhitelistSetEntity> setList = new ArrayList<>();
            if (couponList != null && couponList.size() > 0) {
                for(int i=0; i < couponList.size(); i++) {
                    JSONObject json = JSONObject.parseObject(couponList.getString(i));
                    Integer disTypeId = json.getInteger("disTypeId");
                    Integer count = json.getInteger("count");
                    
                    setEntity = new WhitelistSetEntity();
                    setEntity.setShopId(shopId);
                    setEntity.setLevelId(levelId);
                    setEntity.setDisTypeId(disTypeId);
                    setEntity.setCount(count);
    
                    setList.add(setEntity);
                }
            } else if (levelId != null){
                setEntity = new WhitelistSetEntity();
                setEntity.setShopId(shopId);
                setEntity.setLevelId(levelId);
                
                setList.add(setEntity);
            }
            
            //删除原来的设置
            whiteListMapper.deleteOldSet(shopId);
            if (setList.size() > 0) {
                //插入新设置
                whiteListMapper.insertSetList(setList);
            }
            
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public Map<String, Object> findSetInfo(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            
            List<WhitelistSetEntity> setList = whiteListMapper.selectByShop(shopId);
            Integer levelId = null;
            List<Map<String, Object>> list = new ArrayList<>();
            if (setList.size() > 0) {
                for (WhitelistSetEntity setInfo : setList) {
                    if (null == levelId && setInfo.getLevelId() != null) {
                        levelId = setInfo.getLevelId();
                    }
                    
                    if (setInfo.getDisTypeId() != null) {
                        if(!couponQueryService.checkCouponValidTag(setInfo.getDisTypeId())){
                            continue;
                        }
                        Map<String, Object> map = new HashMap<>();
                        map.put("disTypeId", setInfo.getDisTypeId());
                        map.put("count", setInfo.getCount());
                        list.add(map);
                    }
                }
                
            }
            resultMap.put("levelId", levelId);
            resultMap.put("list", list);
            
            return resultMap;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

}
